package xin.nick.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xin.nick.common.util.MyAssert;
import xin.nick.service.IFileService;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author Nick
 * @since 2022/2/10
 */
@Slf4j
@Service
public class FtpFileServiceImpl implements IFileService {

    /**
     * 配置的本地保存路径
     */
    @Value("${nick.file-upload.path}")
    private String localSavePath;

    /**
     * 配置的上传文件请求目录
     */
    @Value("${nick.file-upload.request-path}")
    private String fileRequestPath;


    /**
     * 项目地址
     */
    @Value("${nick.project-url}")
    private String projectUrl;


    private static String fileSeparator = "/";

    @Override
    public String uploadFile(MultipartFile file) {
        // 获取到文件
        // 登录FTP
        // 将文件保存到指定目录
        // 返回文件名

        // 原始文件名,取出文件后缀
        String originalFilename = file.getOriginalFilename();
        String[] arr = originalFilename.split("\\.");
        String suffix = arr[arr.length - 1];

        // 需要保存的文件名, 带上日期
        String fileName = IdUtil.fastSimpleUUID() + "." + suffix;

        // 目录带上日期
        LocalDateTime now = LocalDateTime.now();
        String dateFolder = "upload/" + now.getYear() +  "/" + now.getMonthValue() + "/" + now.getDayOfMonth();


        FTPClient ftpClient = new FTPClient();
        try {
            // 连接FTP服务器
            ftpClient.connect("192.168.31.161", 21);
            // 登录FTP服务器
//            ftpClient.login("", "");
            // 是否成功登录FTP服务器
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                MyAssert.throwException("登录FTP失败");
            }
            log.info("===========登录FTP成功了==========");

            // ftp保存的目录
            String saveDirectory = dateFolder;
//            boolean hasDirectory = ftpClient.changeWorkingDirectory(saveDirectory);
//            if(!hasDirectory){
//                //不存在文件夹则创建并且进入文件夹
//                ftpClient.makeDirectory(saveDirectory);
//                ftpClient.changeWorkingDirectory(saveDirectory);
//            }

            // 多层文件夹不存在时新建相应的文件夹
            if (!ftpClient.changeWorkingDirectory(saveDirectory)) {
                String tempPath = "";
                // 一层一层判断路径是否存在，不存在就创建
                for (String dir : saveDirectory.split(fileSeparator)) {
                    if ("".equals(tempPath)) {
                        tempPath = dir;
                    } else {
                        tempPath += "/" + dir;
                    }
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        // 创建一个文件夹
                        ftpClient.makeDirectory(tempPath);
                    }
                }
            }


            ftpClient.changeWorkingDirectory(saveDirectory);


            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            // 写出的文件名字
//            String finalFileName =  "/" + dateFolder + "/" + fileName;
            ftpClient.storeFile(fileName, file.getInputStream());

        } catch (Exception e) {
            log.error("上传文件到FTP出错", e);
            MyAssert.throwException("上传文件到FTP出错");
        }

        String resultName = projectUrl + fileRequestPath + "/" + dateFolder + "/" + fileName;
        return resultName;
    }
}
